import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  Image,
  ScrollView,
  TouchableWithoutFeedback,
  PermissionsAndroid,
  Platform,
  Modal,
} from "react-native";
import  LinearGradient from 'react-native-linear-gradient';
import Picker from 'react-native-picker';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
import ActionSheet from "react-native-actionsheet";
import Toast from "../../widget/Toast";
import {
  BaseComponent,
  DatePicker,
} from 'react-native-pickers';
import Loading from "../../widget/Loading";
import NetUtil from "../../net/net_util";
import { width } from "../../util/apdater_util";
import CustomerHeader from "../../widget/customerHeader";
import ImageViewer from 'react-native-image-zoom-viewer';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

class PublishWork extends BaseComponent{
  constructor(props) {
    super(props);
    this.ActionSheet=null;
    this.state={
      isImageViewer:false,
      imageIndex:0,
      previewImageList:[],
      photos:[],
      inputTitle:'',
      industryCateId:'',
      industryCateLabel:'',
      points:'',
      skillCateId:'',
      skillCateLbl:'',
      deadlineTime:'',
      showMask:false,
      date:'',
      DatePicker1:null,
      unit: ['年', '月', '日'],
      startYear:2021,
      endYear:2030,
      industryList:[],
      skillList:[]
    }
  }

  componentWillUnmount() {
    this.dismiss()
  }

  componentDidMount() {
    this.getJobCategoryList(1)
    this.getJobCategoryList(2)
  }

  onChangeText(text){
    this.setState({
      inputTitle:text,
    });
  }
  onChangeValueText(text){
    this.setState({
      inputValue:text
    });
  }

  format(date) {
    let mday = date.getDate();
    let month = date.getMonth() + 1;
    month = month < 10 ? `0${month}` : month;
    mday = mday < 10 ? `0${mday}` : mday;
    return `${date.getFullYear()}-${month}-${mday}`;
  }

  /*获取需求分类*/
  getJobCategoryList(type){
    NetUtil.get('work/job/cate',{type:type},(res)=>{
      if(res.code==200){
        if(type==1)this.setState({industryList:res.data})
        else this.setState({skillList:res.data})
      }
    })
  }

  /*发布需求*/
  submit(){
    let params={
      title:this.state.inputTitle,
      content:this.state.inputValue,
      industryCateId:this.state.industryCateId,
      skillCateId:this.state.skillCateId,
      deadlineTime:this.state.deadlineTime,
      points:this.state.points,
      images:this.state.photos
    }
    Loading.show('正在提交')
    NetUtil.postJson('work/job/create',params,(res)=>{
      Loading.hide()
      if(res.code==200){
        Toast.add('发布成功')
        setTimeout(()=>{
          if(this.props.route.params.callback){
            this.props.route.params.callback()
          }
          this.props.navigation.pop()
        },1500)
      }
      else{
        Toast.add(res.msg)
      }
    })
  }

  //权限
  requestPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: '申请读写手机存储权限',
          message:
            '一个很牛逼的应用想借用你的摄像头，' +
            '然后你就可以拍出酷炫的皂片啦。',
          buttonNeutral: '等会再问我',
          buttonNegative: '不行',
          buttonPositive: '好吧',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('现在你获得摄像头权限了');
      } else {
        console.log('用户并不给你');
      }
    } catch (err) {
      console.warn(err);
    }
  };
  //吊起选择框
  async _imagePicker(){
    if(Platform.OS=='android'){
      this.requestPermission();
    }
    let newPhotos = this.state.photos

    if(newPhotos.length>=3){
      Toast.show("图片最多为3张")
      return
    }
    this.ActionSheet.show()
  }

  //相机拍摄
  selectphotograph(){
    let newPhotos = this.state.photos
    if(newPhotos.length===3){
      Toast.add('最多为三张图片')
      return
    }
    launchCamera({mediaType:'photo',quality:1,selectionLimit:1},({assets})=>{
      if(assets){
        let path=assets[0].uri;
        this.uploadImg(path)
      }
    })
  }

  //相册选择
  selectFromAlbum(){
    launchImageLibrary({mediaType:'photo',quality:1,selectionLimit:1},({assets})=>{
      if(assets){
        let path=assets[0].uri;
        this.uploadImg(path)
      }
    })
  }

  /*上传图片*/
  uploadImg(url){
    Loading.show('正在上传');
    NetUtil.upload('base/upload/file',{path:url},(res)=>{
      Loading.hide()
      if(res.code==200){
        let photos=this.state.photos;
        photos.push(res.data)
        this.setState({photos:photos})
      }
    })
  }

  /**删除图片*/
  deletePhoto(index){
    let photos=this.state.photos;
    photos.splice(index,1);
    this.setState({photos:photos})
  }
  /*预览图片*/
  previewImage(index){
    let photos=this.state.photos;
    let imageList=photos.map((img,idex)=>{
      return {url:img}
    })
    this.setState(
      {imageIndex:index,
        isImageViewer:true,
        previewImageList:imageList})
  }

  pickerShow(type){
    this.setState({showMask:true})
    let pickerData=[];
    let title='';
    if(type==1){
      title='行业分类';
      pickerData=this.state.industryList.map((item)=>{
        return item.name
      })
    }
    else {
      title='技能分类';
      pickerData=this.state.skillList.map((item)=>{
        return item.name
      })
    }
    Picker.init({
      pickerData:pickerData,
      pickerConfirmBtnText:'确定',
      pickerCancelBtnText:'取消',
      pickerTitleText:title,
      pickerBg:[255,255,255,1],
      pickerConfirmBtnColor:[227,147,84,1],
      pickerToolBarBg:[255,255,255,1],
      pickerCancelBtnColor:[51,51,51,1],
      pickerFontSize:20,
      pickerRowHeight:40,
      pickerToolBarFontSize:15,
      onPickerConfirm: (pickedValue) => {
        let value=pickedValue[0]
        if(type==1){
          let industry=this.state.industryList.find((item,index)=>{
            return item.name==value
          })
          this.setState({industryCateId:industry.id,industryCateLabel:industry.name})
        }
        else{
          let skill=this.state.skillList.find((item,index)=>{
            return item.name==value
          })
          this.setState({skillCateId:skill.id,skillCateLbl:skill.name})
        }
        this.dismiss()
      },
      onPickerCancel:()=>{
        this.dismiss()
      }

    })
    Picker.show();
  }
  dismiss(){
    this.setState({showMask:false})
    Picker.hide()
  }
  render() {
    return (
      <View style={styles.container}>
        <CustomerHeader title={'发布需求'} leftOnPress={()=>{this.props.navigation.pop()}}></CustomerHeader>
        <KeyboardAwareScrollView style={{flex:1,paddingLeft:15, paddingVertical:15}} resetScrollToCoords={{ x: 0, y: 0 }}>
          <TextInput style={styles.input} onChangeText={this.onChangeText.bind(this)} value={this.state.inputTitle} placeholder='好的标题帮你吸引更多关注'></TextInput>
          <View style={styles.line}></View>
          <TextInput style={styles.textView} onChangeText={this.onChangeValueText.bind(this)} value={this.state.inputValue} multiline={true} placeholder='问题描述...'></TextInput>
          <View style={styles.imgList}>
            {this.state.photos.map((photo,index)=>{
              return (
                <View style={[styles.imgBox,{marginRight:index<2?10:0}]} key={'photo'+index}>
                  <TouchableWithoutFeedback onPress={this.previewImage.bind(this,index)}>
                    <Image style={{flex:1,borderRadius:4}} source={{uri:photo}}></Image>
                  </TouchableWithoutFeedback>
                  <View style={styles.delete}>
                    <TouchableWithoutFeedback onPress={()=>{this.deletePhoto(index)}}>
                      <Image style={{width:20,height:20}} source={require('../../img/photo_delete_icon.png')}></Image>
                    </TouchableWithoutFeedback>
                  </View>
                </View>
              )
            })}
            {this.state.photos.length>=3?null:(
              <TouchableWithoutFeedback onPress={()=>{this._imagePicker()}}>
              <View style={styles.upload}>
              <Image style={styles.icon} source={require('../../img/photo.png')}></Image>
              <Text style={styles.iconTitle}>上传图片</Text>
              </View>
              </TouchableWithoutFeedback>
              )}
          </View>
          <View style={{marginTop:10}}>
            <TouchableWithoutFeedback onPress={()=>{this.pickerShow(1)}}>
              <View style={styles.cell}>
                <Text style={styles.cellTitle}>行业分类</Text>
                <Text style={[styles.content,{color:this.state.industryCateLabel?'#1C1C1C':'#B7B7B7'}]}>{this.state.industryCateLabel?this.state.industryCateLabel:'请选择'}</Text>
                <Image style={styles.arrow} source={require('../../img/arrow_right_icon.png')}></Image>
              </View>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={()=>{this.pickerShow(2)}}>
              <View style={styles.cell}>
                <Text style={styles.cellTitle}>技能分类</Text>
                <Text style={[styles.content,{color:this.state.skillCateLbl?'#1C1C1C':'#B7B7B7'}]}>{this.state.skillCateLbl?this.state.skillCateLbl:'请选择'}</Text>
                <Image style={styles.arrow} source={require('../../img/arrow_right_icon.png')}></Image>
              </View>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={()=>{this.DatePicker1.show()}}>
              <View style={styles.cell}>
                <Text style={styles.cellTitle}>截稿时间</Text>
                <Text style={[styles.content,{color:this.state.deadlineTime?'#1C1C1C':'#B7B7B7'}]}>{this.state.deadlineTime?this.state.deadlineTime:'请选择'}</Text>
                <Image style={styles.arrow} source={require('../../img/arrow_right_icon.png')}></Image>
              </View>
            </TouchableWithoutFeedback>
              <View style={styles.cell}>
                <Text style={styles.cellTitle}>报酬</Text>
                <TextInput style={styles.content} onChangeText={(text)=>{this.setState({points:text})}} keyboardType={'number-pad'} placeholder={'请填写'}></TextInput>
                <Text style={{color:'#717171'}}>积分</Text>
              </View>
            <TouchableWithoutFeedback onPress={()=>{this.submit()}}>
              <LinearGradient  colors={['#e79c58','#f8da85']} start={{x:0,y:1}} style={styles.publishBtn}>
                <Text style={styles.publishTxt}>发布需求</Text>
              </LinearGradient>
            </TouchableWithoutFeedback>
          </View>
        </KeyboardAwareScrollView>
        <ActionSheet
          ref={o => this.ActionSheet = o}
          title={'请选择照片类型'}
          options={['选择相册', '拍照', '取消']}
          cancelButtonIndex={2}
          destructiveButtonIndex={1}
          onPress={(index) => { if(index===0){this.selectFromAlbum()}else if(index===1){this.selectphotograph()}}}
        />
        <DatePicker
          HH={false}
          mm={false}
          ss={false}
          unit={this.state.unit}
          startYear={this.state.startYear}
          endYear={this.state.endYear}
          onPickerConfirm={(value) => {
            let year=value[0]
            let month=value[1]
            let day=value[2]
            let selectDate=year.substr(0,year.length-1)+'-'+month.substr(0,month.length-1)+'-'+day.substr(0,day.length-1);
            this.setState({deadlineTime:selectDate})
          }}
          onPickerCancel={() => {
            alert('cancel')
          }}
          ref={ref => this.DatePicker1 = ref} />
        {this.state.showMask?(<TouchableWithoutFeedback onPress={this.dismiss.bind(this)}>
          <View style={styles.mask}></View>
        </TouchableWithoutFeedback>):null}
        {this.state.isImageViewer?(
          <Modal transparent={true} visible={true} onRequestClose={()=> {
            this.setState({
              isImageViewer: false,
            });
          }}>
            <ImageViewer enableSwipeDown
                         enableImageZoom={true}
                         onClick={() => { // 图片单击事件
                           this.setState({
                             isImageViewer: false,
                           });
                         }}
                         imageUrls={this.state.previewImageList}
                         onCancel={()=> {
                           this.setState({
                             isImageViewer: false,
                           });
                         }}
                         index={this.state.imageIndex}
                         saveToLocalByLongPress={false}/>
          </Modal>
        ):null}
        <Toast></Toast>
        <Loading></Loading>
      </View>
    )
  }
}

export default module=PublishWork

const styles=StyleSheet.create({
  container:{
    flex:1,
    backgroundColor:'#fff'
  },
  input:{
    height: 50,
    fontSize:18,
    paddingRight:15
  },
  line:{
    backgroundColor: '#F6F6F6',
    height:1
  },
  textView:{
    height:100,
    marginTop:20,
    paddingRight:15
  },
  imgList:{
    flexDirection: 'row',
    justifyContent:'flex-start',
    flexWrap:'nowrap',
    alignItems:'center'
  },
  upload:{
    width:(width-50)/3.0,
    height:(width-50)/3.0,
    justifyContent:'center',
    alignItems:'center',
    borderStyle:'dashed',
    borderWidth:1,
    borderColor:'#DADADA',
    borderRadius:7
  },
  imgBox:{
    width:(width-50)/3.0,
    height:(width-50)/3.0,
    borderRadius:4
  },
  icon:{
    width: 30,
    height:30
  },
  iconTitle:{
    color:'#B7B7B7',
    fontSize: 12
  },
  cell:{
    height:50,
    flexDirection:'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderTopStyle:'solid',
    borderTopWidth:1,
    borderTopColor:'#F7F7F7',
    paddingRight:15
  },
  arrow:{
    width:7,
    height:12
  },
  cellTitle:{
    color:'#1C1C1C',
    fontSize:14
  },
  content:{
    textAlign:'right',
    color:'#1C1C1C',
    fontSize:14,
    flex:1,
    marginRight:10,
  },
  publishBtn:{
    marginHorizontal:12,
    height:44,
    borderRadius: 22,
    marginTop: 35,
    marginRight:27
  },
  publishTxt:{
    flex:1,
    textAlign: 'center',
    lineHeight:44,
    color:'#FFFFFF',
    fontSize:15,
    fontWeight:'500'
  },
  mask:{
    position:'absolute',
    backgroundColor:'rgba(0,0,0,0.6)',
    zIndex:99999,
    top:0,
    left:0,
    right:0,
    bottom:0
  },
  delete:{
    position:'absolute',
    width:20,
    height:20,
    borderRadius:10,
    top:-10,
    right:-8,
    backgroundColor:'#fff',
    zIndex: 99999
  },
  avoidView:{

  }
})
